package Matrix;

import java.util.WeakHashMap;

/**
 * 回旋打印矩阵
 *
 * @author Liaorun
 */
public class PrintMatrixSpiralOrder {

    public static void main(String[] args) {
        int[][] test = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}};

        print(test);

        spiralOrderPrint(test);
    }

    public static void print(int[][] matrix) {

        int rowLength = matrix.length;
        int colLength = matrix[0].length + 1;

        int curRow = 0, curCol = -1;

        // 向上和向右的时候需要-1的长度,一开始要把col长度多给1

        while (colLength != 0 && rowLength != 0) {
            // right
            colLength--;

            for (curCol++; curCol < colLength; curCol++) {
                System.out.println(matrix[curRow][curCol]);
            }
            curCol--;

            // down
            for (curRow++; curRow < rowLength; curRow++) {
                System.out.println(matrix[curRow][curCol]);
            }
            curRow--;

            // left
            for (curCol--; curCol >= matrix[0].length - colLength; curCol--) {
                System.out.println(matrix[curRow][curCol]);
            }
            curCol++;

            // top
            rowLength--;

            for (curRow--; curRow >= matrix.length - rowLength; curRow--) {
                System.out.println(matrix[curRow][curCol]);
            }
            curRow++;
        }

    }

    public static void spiralOrderPrint(int[][] matrix) {
        // 左上角的行
        int tR = 0;
        // 左上角的列
        int tC = 0;
        // 右上角的行
        int dR = matrix.length - 1;
        //右上角的列
        int dC = matrix[0].length - 1;
        // 跳出条件:左上角点行> 右下角点行坐标 ||  左上角的列 > 右上角的列
        while (tR <= dR && tC <= dC) {
            // 左上架点向右下方移动，同时右下角点向左上方移动
            printEdge(matrix, tR++, tC++, dR--, dC--);
        }
    }

    /**
     * @param matrix 矩阵
     * @param a      左上角的行
     * @param b      左上角的列
     * @param c      右上角的行
     * @param d      右上角的列
     */
    private static void printEdge(int[][] matrix, int a, int b, int c, int d) {

        if (a == c) {
            for (int i = b; i <= d; i++) {
                System.out.println(matrix[a][i]);
            }
        } else if (b == d) {
            for (int i = a; i <= c; i++) {
                System.out.println(matrix[i][b]);
            }
        } else {
            int curC = b;
            int curR = a;
            while (curC != d) {
                System.out.println(matrix[a][curC]);
                curC++;
            }

            while (curR != c) {
                System.out.println(matrix[curR][d]);
                curR++;
            }

            while (curC != b) {
                System.out.println(matrix[c][curC]);
                curC--;
            }

            while (curR != a) {
                System.out.println(matrix[curR][b]);
                curR--;
            }
        }
    }
}
